<?php
session_start();

if(isset($_SESSION['authorised']) && $_SESSION['authorised'] == true)
{   
    if(isset($_SESSION['type']))
    {
        if($_SESSION['type'] == 'administrator')
        {
            $dbname = $_SESSION['database'];
           
			$lastname=strtoupper(addslashes(pg_escape_string($_POST['last_name'])));
			$firstname=strtoupper(addslashes(pg_escape_string($_POST['first_name'])));
			$middlename=strtoupper(addslashes(pg_escape_string($_POST['middle_name'])));
			$username= $_POST['email'];
			$stadd1=strtoupper(addslashes(pg_escape_string($_POST['street_add_1'])));
			$stadd2=strtoupper(addslashes(pg_escape_string($_POST['street_add_2'])));
			$city=strtoupper(addslashes(pg_escape_string($_POST['city_add'])));
			$contact_num=addslashes(pg_escape_string($_POST['contact_num']));
			$password=addslashes(pg_escape_string($_POST['pass1']));
			$acctype=strtolower(addslashes(pg_escape_string($_POST['accType'])));
            
			include('connection.inc');
            
            $sql = "SELECT * FROM users where username='$username'";
            $result = pg_query($sql);
            
            $count = pg_num_rows($result);
            
            if($count >= 1)
            {
                echo 'Username already exists';
                header('Location: accountcreation.php');
                exit();
            }
            else
            {
                $sql="INSERT INTO users (username, password, usertype, lastname, firstname, middlename, streetAdd1, streetAdd2, cityAdd, contactNum) VALUES ('$username','$password', '$acctype', '$lastname','$firstname','$middlename', '$address1','$address2','$city','$contact_num')";
				$result=pg_query($sql);
				$_SESSION['account_name']=$username;
                if($usertype=='STUDENT')
				{
					header('Location: create_student.php');
					exit();
				}
				elseif($usertype=='PARENT')
				{
					$sql="INSERT INTO users (username) values ($username)"
					$result=pg_query($sql);
					header('Location: manageaccounts.php');
					exit();
				}
				elseif($usertype=='TUTOR')
				{
					header('Location: create_tutor.php');
					exit();
				}
            }
        }
        elseif($_SESSION['type'] == 'student')
        {
            header('Location: studentindex.php');
            exit();
        }
        elseif($_SESSION['type'] == 'tutor')
        {
            header('Location: tutorindex.php');
            exit();
        }
        elseif($_SESSION['type'] == 'parent')
        {
            header('Location: parentindex.php');
            exit();
        }
    }
}
else
{
    header('Location: index.php');
}
?>
